<template>
    <div class="app-container">
      <div class="de-main">
          <el-alert v-if="!surveyStatus" :title="tips" type="error" :closable="false"/>
          <div class="s-box">
            <h2 class="s-title">{{ survey.surveyName }}</h2>
            <div class="s-desc">
              {{ survey.surveyDesc }}
            </div>
          </div>
          <div class="s-quesitions">
            <Question 
              v-for="(question, i) in questionList" 
              :question="question" 
              :surveyId="surveyId" 
              :index="i"
              :key="question.questionNo"/>
          </div>
  
          <div class="s-btn" v-if="surveyStatus">
            <el-button type="primary" @click="saveData(1)">保存</el-button>
            <el-button type="default" @click="saveData(0)">暂存</el-button>
          </div>
        </div>
        <el-backtop :right="10" :bottom="10" />
    </div>
  </template>
  <script>
  import FingerprintJS from '@fingerprintjs/fingerprintjs';
  import Question from './question/question_view.vue';
  import { getSurvey } from "@/api/survey/survey";
  import { listBySurveyId } from "@/api/survey/question";
  import { listJsonAn, addJsonAn, updateJsonAn } from "@/api/survey/answer";
  export default {
    name: 'Preview',
    // dicts: [],
    components: { Question },
    data(){
      return {
        deviceId: '',
        surveyId: this.$route.params.id,
        anId: '',
        survey: {},
        questionList: [],
        surveyStatus: true,
        tips: '',
      }
    },
    async mounted(){
      const fp = await FingerprintJS.load();
      const result = await fp.get();
      this.deviceId = result.visitorId;

      this.surveyId = this.$route.params.id;
      this.getSurvey();
      this.getQuestionList();
    },
    methods:{
      /** 获取问卷对象 */
      getSurvey(){
        getSurvey(this.surveyId).then(response => {
          this.survey = response;
          if(this.survey.surveyStatus == 0){
            this.surveyStatus = false;
            this.tips = '该问卷尚未发布，暂不能收集！'
          }
          if(this.survey.surveyStatus == 2){
            this.surveyStatus = false;
            this.tips = '该问卷已结束，无法收集！'
          }
          if(this.survey.surveyStatus == 1){
            this.surveyStatus = true;
          }
        });
      },
      /** 获取问题列表 */
      async getQuestionList(){
        const jsonAn = await this.getAnswerJson();
        console.log("answer",jsonAn);
        listBySurveyId(this.surveyId).then(response => {
          this.questionList = response;
          this.questionList = this.questionList.map((item) => {
            if(jsonAn.length > 0){
              const answers = JSON.parse(jsonAn[0].answerJson)
              for (let json of answers){
                if(item.questionId === json.questionId){
                  item.answer = json;
                  break;
                }
              }
            } else {
              item.answer = {
                questionId: item.questionId,
                answerValue: '',
                extendValue: '',
              }
            }
            return item;
          })
          console.log("questionList",this.questionList);
        })
      },
      async getAnswerJson(){
        const params = {
          surveyId: this.surveyId,
          deviceId: this.deviceId,
        }
        return await listJsonAn(params)
      },
      saveData(state){
        const json = this.questionList.map(item => {
          return {
            questionId: item.questionId,
            answerValue: item.answer.answerValue,
            extendValue: item.answer.extendValue,
          }
        });
        const data = {
          anId: this.anId,
          surveyId: this.surveyId,
          dataState: state,
          deviceId: this.deviceId,
          answerJson: JSON.stringify(json),
        }
        console.log(data);
        if(this.anId){
          updateJsonAn(data).then(response => {
            this.$message({
              message: '保存成功',
              type:'success',
              duration: 1500,
            });
            // this.getQuestionList();
            this.$router.push({path: "/collect/complete"});
          })
          return;
        }
        addJsonAn(data).then(response => {
          console.log(response);
          this.anId = response;
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 1500,
          });
          this.$router.push({path: "/collect/complete"});
        })
      },
    }
  }
  </script>
  <style scoped>
  .app-container{
    background: #f0f0f0;
  }
  .de-main{
    background:  #fff;
    width:  100%;
    max-width: 50rem;
    margin: 0 auto;
    position: relative;
    overflow-y: auto;
  }
  .de-main .el-backtop{
    position: absolute;
  }
  .s-title{
    text-align: center;
    padding: 5rem 0 4rem 0;
    margin: 0;
  }
  .s-desc{
    text-indent: 2em;
    border-bottom: 1px solid #eaeaea;
    padding: 6px 20px;
  }
  .s-btn{
    text-align:center;
    padding-bottom: 5rem;
  }
  </style>